package com.zyh.record.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zyh.common.annotation.Log;
import com.zyh.common.core.controller.BaseController;
import com.zyh.common.core.domain.AjaxResult;
import com.zyh.common.enums.BusinessType;
import com.zyh.common.utils.SecurityUtils;
import com.zyh.common.utils.StringUtils;
import com.zyh.record.domain.ExamRecord;
import com.zyh.record.service.ExamRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

/**
 * 测评记录管理
 *
 * @author ZYH
 * @version 1.0
 * @date 2025-02-23
 */
@RestController
@RequestMapping("/record/record")
public class ExamRecordController extends BaseController {
    @Autowired
    private ExamRecordService examRecordService;

    /**
     * 对比历史记录
     *
     * @param currentId
     * @param historyId
     * @return
     */
    @GetMapping("/compareHistoryRecord")
    public AjaxResult compareHistoryRecord(@RequestParam("currentId") Long currentId,
                                           @RequestParam("historyId") Long historyId) {
        logger.info("compareHistoryRecord入参currentId-->{},historyId-->{}", currentId,historyId);
        return examRecordService.compareHistoryRecord(currentId, historyId);
    }

    /**
     * 根据用户id，测评卷id，查询用户是否已经测评过该卷
     *
     * @param paperId
     * @return
     */
    @GetMapping("/checkRecord/{paperId}")
    public AjaxResult checkRecord(@PathVariable("paperId") Long paperId) {
        ExamRecord recordObj = getExamRecordByPaperId(paperId);
        if (Objects.isNull(recordObj)) {
            // 没有测评记录
            return AjaxResult.success("查询成功", null);
        } else if ("0".equals(recordObj.getStatus()) || "2".equals(recordObj.getStatus())) {
            // 有测评记录，并且状态为进行中
            return AjaxResult.success("查询成功", recordObj);
        } else {
            // 1 已结束
            return null;
        }
    }

    /**
     * 添加一条测评记录
     *
     * @return
     */
    @PostMapping("/add/{paperId}")
    public AjaxResult add(@PathVariable("paperId") Long paperId) {
        logger.info("add入参->{}", paperId);
        ExamRecord record = getExamRecordByPaperId(paperId);
        if (Objects.nonNull(record) && StringUtils.isNotEmpty(record.getStatus()) && "0".equals(record.getStatus())) {
            return AjaxResult.success();
        } else if (Objects.nonNull(record) &&
                StringUtils.isNotEmpty(record.getStatus()) &&
                "2".equals(record.getStatus())) {
            // 从暂停恢复，只更新最后开始时间
            record.setLastStartTime(new Date());
            record.setStatus("0");
            return toAjax(examRecordService.updateById(record));
        } else {
            // 如果没有记录，则新增一条记录
            ExamRecord examRecord = new ExamRecord();
            examRecord.setUserId(SecurityUtils.getUserId());
            examRecord.setPaperId(paperId);
            examRecord.setTotalScore(0);    // 设置总分初始值为0
            examRecord.setStatus("0");      // 设置状态为进行中
            examRecord.setStartTime(new Date());    // 设置开始时间
            examRecord.setLastStartTime(new Date());
            examRecord.setTotalTime(0L);
            examRecord.setCreateBy(SecurityUtils.getUsername());
            logger.info("新增测评记录");
            return toAjax(examRecordService.save(examRecord));
        }
    }

    /**
     * 提交测评
     *
     * @param paperId
     * @return
     */
    @Log(title = "测评提交", businessType = BusinessType.UPDATE)
    @PostMapping("/submitPaper/{paperId}")
    public AjaxResult submitPaper(@PathVariable("paperId") Long paperId) {
        logger.info("submitPaper入参assessments-->{}", paperId);
        ExamRecord record = getExamRecordByPaperId(paperId);
        if (Objects.nonNull(record) && "1".equals(record.getStatus())) {
            return AjaxResult.error("测评已结束，不可重复提交！");
        }
        // 计算本次持续时间并累加
        long currentDuration = System.currentTimeMillis() - record.getLastStartTime().getTime();
        record.setTotalTime(record.getTotalTime() + currentDuration);

        // 更新时间状态
        record.setStatus("1");
        record.setSubmitTime(new Date());
        record.setLastStartTime(null); // 提交后清空最后开始时间
        return examRecordService.submitPaper(record) > 0
                ? AjaxResult.success("提交成功！") : AjaxResult.error();
    }


    /**
     * 点击退出按钮时保存当前测评记录
     *
     * @param paperId
     * @return
     */
    @PostMapping("/saveCurrentRecord/{paperId}")
    public AjaxResult saveCurrentRecord(@PathVariable("paperId") Long paperId) {
        logger.info("saveCurrentRecord入参paperId-->{}", paperId);
        ExamRecord record = getExamRecordByPaperId(paperId);
        if (Objects.isNull(record) || !"0".equals(record.getStatus())) {
            return AjaxResult.error("无进行中的测评记录");
        }
        // 计算当前会话耗时并累加
        long currentDuration = System.currentTimeMillis() - record.getLastStartTime().getTime();
        record.setTotalTime(record.getTotalTime() + currentDuration);

        // 更新状态为暂停
        record.setStatus("2");
        record.setLastStartTime(null); // 暂停后清空最后开始时间
        return toAjax(examRecordService.submitPaper(record));
    }

    /**
     * 重新测评
     *
     * @param paperId
     * @return
     */
    @Log(title = "重新测评", businessType = BusinessType.UPDATE)
    @PostMapping("/retestAssessment/{paperId}")
    public AjaxResult retestAssessment(@PathVariable("paperId") Long paperId) {
        logger.info("retestAssessment入参paperId-->{}", paperId);
        ExamRecord record = getExamRecordByPaperId(paperId);
        if (Objects.nonNull(record) && "1".equals(record.getStatus())) {
            record.setStatus("1");
            record.setDelFlag("2");
            // 重置开始时间和提交时间
            record.setStartTime(null);
            record.setSubmitTime(null);
            record.setTotalTime(null);
        }
        logger.info("查询出来的record对象-->{}", record);
        return toAjax(examRecordService.updateById(record));
    }

    /**
     * 获取最近一次的历史数据
     */
    /*@GetMapping("/getHistoryData/{paperId}")
    public AjaxResult getHistoryData(@PathVariable("paperId") Long paperId) {
        // 根据useId,paperId,status,delFlag查询出最近一次的测评记录并按照createTime 倒序排列
        ExamRecord record = examRecordService.getOne(new LambdaQueryWrapper<ExamRecord>()
                .eq(ExamRecord::getUserId, SecurityUtils.getUserId())
                .eq(ExamRecord::getPaperId, paperId)
                .eq(ExamRecord::getStatus, "1")
                .eq(ExamRecord::getDelFlag, "2")
                .orderByDesc(ExamRecord::getCreateTime)
                .last("limit 1"));
        AnalyzeDataObj oldAnalyzeDataObj = null;
        if (Objects.nonNull(record)) {
            oldAnalyzeDataObj = userAnswerServiceImpl.getScore(paperId);
        }
        return Objects.nonNull(oldAnalyzeDataObj) ?
                AjaxResult.success("查询成功", oldAnalyzeDataObj) : AjaxResult.success("无记录");
    }*/


    /**
     * 公共方法：根据 userId, paperId  , delFlag查询测评记录
     *
     * @param paperId
     * @return
     */
    public ExamRecord getExamRecordByPaperId(Long paperId) {
        return examRecordService.getOne(
                new LambdaQueryWrapper<ExamRecord>()
                        .eq(ExamRecord::getUserId, SecurityUtils.getUserId())
                        .eq(ExamRecord::getPaperId, paperId)
                        .eq(ExamRecord::getDelFlag, "0"));
    }
}
